package cn.itcast.bos.service.base.impl;

import cn.itcast.bos.dao.base.AreaRepository;
import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.ExcelUtils;
import cn.itcast.bos.utils.PinYin4jUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;

@Service
@Transactional
public class AreaServiceImpl implements AreaService {

    @Autowired
    private AreaRepository areaRepository;

    @Override
    public void uploadArea(File file, String filename) {

        //读取Excel文件进行解析，并形成城市简码
        Sheet sheet = ExcelUtils.getExcelSheetByFile(file, filename);
        ArrayList<Area> areas = new ArrayList<>();
        System.out.println(filename+"---");
        //遍历拿到的sheet文件（单页）
        for (Row row:sheet) {
            if(row.getRowNum()>0){
                String id = row.getCell(0).getStringCellValue();
                String province = row.getCell(1).getStringCellValue();
                String city = row.getCell(2).getStringCellValue();
                String district = row.getCell(3).getStringCellValue();
                String postcode = row.getCell(4).getStringCellValue();
                Area area = new Area();
                area.setId(id);
                area.setProvince(province);
                area.setCity(city);
                area.setDistrict(district);
                area.setPostcode(postcode);

                //使用工具设置区域编码
                String[] headByString = PinYin4jUtils.getHeadByString(province + city + district);
                String str = StringUtils.join(headByString, "");
                area.setShortcode(str);

                //设置城市简码
                String s = PinYin4jUtils.hanziToPinyin(province + city + district);
                area.setCitycode(s);
                areas.add(area);

            }
        }
//        areaRepository.save(areas);



    }

    @Override
    public Page<Area> findPageData(Specification<Area> specification, Pageable pageable) {
        Page<Area> all = areaRepository.findAll(specification, pageable);
        return all;
    }

    @Override
    public Area findOne(String areaId) {
        Area one = areaRepository.findOne(areaId);
        return one;
    }
}
